type EventListener<T> = (data: T) => void;

class EventCenter<T> {
    private static instance: EventCenter<any>;
    private events = new Map<string, EventListener<T>[]>();

    public static getInstance(): EventCenter<any> {
        if (!EventCenter.instance) {
          EventCenter.instance = new EventCenter();
        }
        return EventCenter.instance;
      }

    // 订阅事件
    on(eventName: string, listener: EventListener<T>) {
        if (!this.events.has(eventName)) {
            this.events.set(eventName, []);
        }
        const listeners = this.events.get(eventName);
        listeners.push(listener);
    }

    // 取消订阅事件
    off(eventName: string, listener: EventListener<T>) {
        if (this.events.has(eventName)) {
            const listeners = this.events.get(eventName);
            const index = listeners.indexOf(listener);
            if (index > -1) {
                listeners.splice(index, 1);
            }
        }
    }

    // 触发事件
    emit(eventName: string, data: T) {
        if (this.events.has(eventName)) {
            const listeners = this.events.get(eventName);
            listeners.forEach((listener) => {
                listener(data);
            });
        }
    }
}

export default EventCenter
